#include <iostream>
#include <Ice/Ice.h>
#include <IceUtil/IceUtil.h>
#include <BidirectionImpl.h>
#include <BirConnection.h>
#include <condition_variable>
#include <mutex>

std::condition_variable g_cv;
std::mutex g_Mtx;

bool g_bRet;

void OnClientClose();

bool ConnectToServer();

int main()
{
#ifdef _WIN32
	system("chcp 65001");
#endif
	while (true) {
		try {
			std::cout << "开始连接服务器" << std::endl;
			g_bRet = ConnectToServer();
			if (g_bRet) {
				std::cout << "连接服务器成功" << std::endl;
				//暂停程序
				std::unique_lock<std::mutex> lck(g_Mtx);
				g_cv.wait(lck, [] {
					return !g_bRet;
				});
			}
		}
		catch (const ::Ice::Exception& ex) {
			std::cout << "Ice出现异常:" << ex.what() << std::endl;
			g_bRet = false;
		}
		Sleep(1000);
	}
	return 0;
}

bool ConnectToServer()
{
	::Ice::CommunicatorPtr ic = ::Ice::initialize();
	Ice::ObjectPrx base = ic->stringToProxy("sender:default -h 192.168.3.114 -p 10000");
	Demo::CallbackSenderPrx server = Demo::CallbackSenderPrx::checkedCast(base);

	const std::string clientID = ::IceUtil::generateUUID();
	//注册心跳连接函数
	::Ice::ConnectionPtr conn = server->ice_getConnection();
	conn->setACM(5, ::Ice::CloseOnInvocationAndIdle, ::Ice::HeartbeatAlways);
	BirConnection* pBirConn = new BirConnection();
	std::shared_ptr<std::function<void()>> pCloseHandler = std::make_shared<std::function<void()>>(&OnClientClose);
	pBirConn->SetClientCloseHandler(pCloseHandler);
	conn->setCallback(pBirConn);
	if (!server) {
		std::cout << "服务端代理指针为空" << std::endl;
		return false;
	}
	server->registerConntionHandler(clientID);

	//建立双向数据连接
	::Ice::ObjectAdapterPtr adapter = ic->createObjectAdapter("");

	Ice::Identity ident;
	ident.name = clientID;
	ident.category = "";

	adapter->add(new Demo::CallbackReceiverImpl, ident);
	adapter->activate();

	server->ice_getConnection()->setAdapter(adapter);
	server->addClient(ident);
	return true;
}

void OnClientClose()
{
	g_bRet = false;
	g_cv.notify_all();
}